package com.cpj.idGenerator.impl;

import com.cpj.idGenerator.IdGeneratorService;
import com.cpj.utils.DateUtils;
import com.cpj.utils.GeneratorRedisUtil;
import com.cpj.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;

@Service
public class IdGeneratorServiceImpl implements IdGeneratorService {
    @Autowired
    GeneratorRedisUtil generatorRedisUtil;
    @Override
    public String idGenerator(String key) {
        int timeout = -1;
        long id = generatorRedisUtil.incr(key, timeout); //使用redis获取自增ID
        System.out.println("insert into order_id(id) values('"+DateUtils.format(new Date(), "yyyyMMddHH") + num2str(id,4)+"');");//00001  00002 ... 10001
        return DateUtils.format(new Date(), "yyyyMMddHH") + num2str(id,4);
    }

    @Override
    public String idGenerator(String key, String prefix) {
        return prefix+this.idGenerator(key);
    }

    private static String num2str(long num, int weishu) {
        String s = num + "";
        int len = s.length();
        String result = "";
        for (int i = 0; i < weishu - len; i++) {
            result = result + '0';
        }
        result = result + s;
        //截取超长字段
        if(len>weishu){
            result = result.substring(len-weishu);
        }
        return result;
    }
}
